<template>
  <div class="account">
    <el-card>
      <el-form
        ref="formRef"
        :rules="formRules"
        :model="formData"
        label-width="auto">
        <el-form-item
          prop="account"
          label="账户名">
          <el-input
            v-model.trim="formData.account"
            placeholder="账户名"
            disabled
            clearable>
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="oldPassword"
          label="旧密码">
          <el-input
            v-model.trim="formData.oldPassword"
            clearable
            placeholder="旧密码"
            show-password>
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="newPassword"
          label="新密码">
          <el-input
            v-model.trim="formData.newPassword"
            clearable
            placeholder="新密码"
            show-password>
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-button
          class="submit"
          type="warning"
          @click="updatePassword">
          修改密码
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useValidator } from "@/hooks/useValidator";
import ApiSysUser from "@/api/modules/sys-user"
import message from "@/common/element-plus/message";
import md5 from "js-md5";
import { useUserStore } from "@/stores/user";

/** store */
const userStore = useUserStore()

const formData = ref({})
formData.value.account = userStore.userInfo.account

const formRef = ref()

/** 校验 */
const { required, validate } = useValidator()

/** 表单规则 */
const formRules = {
  account: [required("账户名")],
  oldPassword: [required("旧密码")],
  newPassword: [required("新密码")]
}

const updatePassword = async () => {
  await validate(formRef.value)
  await ApiSysUser.updatePassword({
    account: formData.value.account,
    oldPassword: md5(formData.value.oldPassword),
    newPassword: md5(formData.value.newPassword),
  })
  message.success()
}
</script>

<style lang="scss" scoped>
.account {
  .submit {
    width: 100%;
  }
}
</style>